package com.luoxiang.socialandroid.activity

import android.content.Intent
import android.content.IntentSender
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import com.facebook.CallbackManager
import com.facebook.FacebookCallback
import com.facebook.FacebookException
import com.facebook.login.LoginResult
import com.google.android.gms.auth.api.identity.BeginSignInRequest
import com.google.android.gms.auth.api.identity.Identity
import com.google.android.gms.auth.api.identity.SignInClient
import com.google.android.gms.common.api.ApiException
import com.luoxiang.socialandroid.R
import com.luoxiang.socialandroid.base.BaseActivity
import com.luoxiang.socialandroid.databinding.ActivityOverseasLoginBinding

class OverseasLoginActivity : BaseActivity() {
    private lateinit var mViewBinding: ActivityOverseasLoginBinding
    private lateinit var oneTapClient: SignInClient
    private lateinit var signInRequest: BeginSignInRequest
    private val REQ_ONE_TAP = 10001

    override fun initLayout(savedInstanceState: Bundle?) {
        mViewBinding = ActivityOverseasLoginBinding.inflate(layoutInflater)
        setContentView(mViewBinding.root)
    }

    override fun initView() {
        mViewBinding.loginFacebook.setPermissions("email")
        oneTapClient = Identity.getSignInClient(this)
        signInRequest = BeginSignInRequest.builder()
            .setPasswordRequestOptions(BeginSignInRequest.PasswordRequestOptions.builder()
                .setSupported(true)
                .build())
            .setGoogleIdTokenRequestOptions(
                BeginSignInRequest.GoogleIdTokenRequestOptions.builder()
                    .setSupported(true)
                    // Your server's client ID, not your Android client ID.
                    .setServerClientId(getString(R.string.google_auth))
                    // Only show accounts previously used to sign in.
                    .setFilterByAuthorizedAccounts(false)
                    .build())
            // Automatically sign in when exactly one credential is retrieved.
            .setAutoSelectEnabled(true)
            .build()
    }

    override fun initListener() {
        mViewBinding.loginFacebook.registerCallback(CallbackManager.Factory.create(),
            object : FacebookCallback<LoginResult> {
                override fun onSuccess(result: LoginResult) {
                    Toast.makeText(
                        this@OverseasLoginActivity,
                        getString(R.string.mi_dengluchenggong_2)+result.accessToken.token+result.accessToken.userId,
                        Toast.LENGTH_SHORT
                    ).show()
                }

                override fun onCancel() {
                    Toast.makeText(this@OverseasLoginActivity, getString(R.string.mi_dengluquxiao), Toast.LENGTH_SHORT).show()
                }

                override fun onError(error: FacebookException) {
                    Toast.makeText(
                        this@OverseasLoginActivity,
                        getString(R.string.mi_denglushibai)+":${error.message}",
                        Toast.LENGTH_SHORT
                    ).show()
                }
            })
        mViewBinding.imageGoogleLogin.setOnClickListener {
            oneTapClient.beginSignIn(signInRequest)
                .addOnSuccessListener(this) { result ->
                    try {
                        startIntentSenderForResult(
                            result.pendingIntent.intentSender, REQ_ONE_TAP,
                            null, 0, 0, 0, null)
                    } catch (e: IntentSender.SendIntentException) {
                        Log.e("OverseasLoginActivity", "Couldn't start One Tap UI: ${e.localizedMessage}")
                    }
                }
                .addOnFailureListener(this) { e ->
                    // No saved credentials found. Launch the One Tap sign-up flow, or
                    // do nothing and continue presenting the signed-out UI.
                    Log.d("OverseasLoginActivity", e.localizedMessage)
                }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        when (requestCode) {
            REQ_ONE_TAP -> {
                try {
                    val credential = oneTapClient.getSignInCredentialFromIntent(data)
                    val idToken = credential.googleIdToken
                    val username = credential.id
                    val password = credential.password
                    when {
                        idToken != null -> {
                            // Got an ID token from Google. Use it to authenticate
                            // with your backend.
                            Log.d("OverseasLoginActivity", "$idToken $username")
                        }
                        password != null -> {
                            // Got a saved username and password. Use them to authenticate
                            // with your backend.
                            Log.d("OverseasLoginActivity", "Got password.")
                        }
                        else -> {
                            // Shouldn't happen.
                            Log.d("OverseasLoginActivity", "No ID token or password!")
                        }
                    }
                } catch (e: ApiException) {
                    Log.d("OverseasLoginActivity", e.message.toString())
                }
            }
        }
    }
}